package com.interauto.service;

import com.alibaba.fastjson.JSONObject;
import com.interauto.AppliCation;
import com.interauto.Dao.Mapper.MgRunTaskInter;
import com.interauto.Dao.entity.Runtasktable;
import com.interauto.service.kaklis.RunTaskProducer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

import static com.interauto.util.Utils.getTimemm;

/**
 * 处理任务运行相关哈
 */
@Component
public class AutoRunTaskinfoService {
    private static final Logger logger= LoggerFactory.getLogger(AutoRunTaskinfoService.class);
    @Autowired
    private MgRunTaskInter mgRunTaskInter;
    @Autowired
    private RunTaskProducer runTaskProducer;

    @Scheduled(cron = "0 */1 * * * ? ")
    private void taskinit(){
        try{
            List<Runtasktable> runtasktableList=mgRunTaskInter.getGoRuntasks();
            if(runtasktableList == null || runtasktableList.isEmpty()){
                logger.info("-->> getGoRuntasks is empty");
            }
            for(Runtasktable task:runtasktableList){
                String caseinfos=task.getCaseinfo();
                int runcyle=task.getRuncycle();
                if(StringUtils.isEmpty(caseinfos) || runcyle<1){
                    logger.info("-->> no run;task is:"+task.toString());
                    continue;
                }
                int timemm=getTimemm();
                if(timemm%runcyle != 0){
                    logger.info("未达到配置时间,跳过该任务,任务ID:"+task.getId());
                    continue;
                }
                String taskjson= JSONObject.toJSONString(task);
                runTaskProducer.addtaskinfo(taskjson);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx=new SpringApplicationBuilder(AppliCation.class).run(args);
        AutoRunTaskinfoService appliCation=ctx.getBean("autoRunTaskinfoService",AutoRunTaskinfoService.class);
        appliCation.taskinit();
    }
}
